// src/api/user.js
import request from '@/utils/request';
import service from "@/utils/request";

/**
 * 用户登录
 * @param {{password: string, role: string, user: string}} data - 登录表单数据
 * @param {string} data.username - 用户名
 * @param {string} data.password - 密码

 * @returns {Promise<Object>} - 包含 token 和用户信息的响应
 */

export function login(data) {
    return request.post('/api/login', data);
}
/**
 * 登录API by Sa-token
 * @param {string} username - 用户名
 * @param {string} password - 密码
 */
export function loginTest(username, password) {
    return service.post('/api/login/loginTest', {
        username,
        password
    }).then(res => {
        // 登录成功后，将token和用户信息存储到本地存储
        if (res.status === 'success') {
            localStorage.setItem('satoken', service.defaults.headers['Authorization'])
            // 这里可以根据后端返回的数据结构调整
            // localStorage.setItem('userInfo', JSON.stringify(res.data.user))
        }
        return res
    })
}
/**
 * 获取用户信息
 * @returns {Promise<Object>} - 用户信息
 */
export function getUserInfo() {
    return request.get('/api/user/info');
}
export function getCurrentUserPermissions(){
    return request.get('/api/login/currentUserPermissions');
}
/**
 * 退出登录
 * @returns {Promise<void>}
 */
export function logout() {
    return request({
        url: '/api/login/logout', // 对应后端的接口路径
        method: 'post'
    }).then(res => {
        // 退出成功后，清除本地存储的satoken
        localStorage.removeItem('satoken')
        localStorage.removeItem('userPermissions')
        return res
    })
}
export function userlist(params) {
    return request.get('/api/usermanage/list',{ params});
}
export function roleList(params) {
    return request.get('/api/usermanage/rolelist',{ params});
}
export function getRole() {
    return request.get('/api/usermanage/role');
}
export function addOrUpdate(data) {
    return request.post('/api/usermanage/addorupdate', data);
}
export function deleteUser(id) {
    return request.delete(`/api/usermanage/delete/${id}`);
}
export function batchDelete(ids) {
    return request.post('/api/usermanage/batch_delete', ids );
}
export function addRole(data){
    return request.post('/api/usermanage/addrole', data);
}
export function updateRole(data){
    return request.post('/api/usermanage/updaterole', data);
}
export function deleteRole(id) {
    return request.delete(`/api/usermanage/deleterole/${id}`);
}
export function getAllPermissions() {
    return request.get('/api/usermanage/permissions/all');
}
export function getRolePermissions(roleId) {
    return request.get(`/api/usermanage/${roleId}/permissions`);
}
export function saveRolePermissions(roleId, permissionIds) {
    return request.post(`/api/usermanage/${roleId}/permissions`,permissionIds);
}